<template>
  <div>
    <el-tree
      :data="data"
      node-key="id"
      default-expand-all
      @node-drag-end="handleDragEnd"
      draggable
      :allow-drop="allowDrop"


      :expand-on-click-node="false"
      :render-content="renderContent"
    >
    </el-tree>
    <!--  此处一定要加个div，用v-if来控制，不然对话框的数据不会变  -->
    <div v-if="dialogVisible">
      <el-dialog
        :visible.sync="dialogVisible"
        width="30%"
        >

        <update-menu :selectedId="selectedId"></update-menu>

      </el-dialog>

    </div>

  </div>

</template>
<script>
import qs from "qs";
import CryptoJS from "crypto-js"
import UpdateMenu from "./updateMenu";

let id = 0;
export default {
  name: "Menu_config",
  components: {UpdateMenu},
  provide() {
    return {
      dialog_close: this.shutDown_dialog,
    }
  },
  data() {
    return {
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      dialogVisible: false,
      selectedId: "",
    };
  },
  /**
   * 获取菜单数据
   */
  created() {
    let that = this;
    this.axios.post('http://localhost:8080/getMenu_config').then(function (res) {
      /*console.log(res.data)*/
      that.data = res.data.menu
      id = res.data.maxlevel + 1
    })
  },
  methods: {
    /**
     * 关闭弹窗
     */
    shutDown_dialog() {
      this.dialogVisible = false;
    },



    /**
     * 拖拽结束后的操作
     */
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      /*console.log(dropNode.level,draggingNode.level)*/

      let list2 = [];
      let childnodes = "";
      let parent_id = 0;

      if (dropNode.level === draggingNode.level) {
        this.list = []
        //将同级的数据的id取出来放到list
        for (let item of dropNode.parent.childNodes) {
          this.list.push(item.data.id)
        }
        //将list排序
        this.list.sort(function (a, b) {
          return a - b;
        })
        //再将排序后的id重新分配，达到排序的目的
        for (let i = 0; i < dropNode.parent.childNodes.length; i++) {
          dropNode.parent.childNodes[i].data.id = this.list[i];
        }
        childnodes = dropNode.parent.childNodes
        if (dropNode.parent.data.idKey == null) {
          parent_id = 0;
        } else {
          parent_id = dropNode.parent.data.idKey
        }
        /*   console.log(dropNode.parent.childNodes)
         console.log(dropNode.parent.data.idKey)*/

      } else if (draggingNode.level - dropNode.level === 1) {
        childnodes = dropNode.childNodes

        parent_id = dropNode.data.idKey
        /*  console.log(dropNode.childNodes)
          console.log(dropNode.data.idKey)*/
      }

      for (let item2 of childnodes) {
        list2.push(item2.data)
      }


      let data = {
        "json": JSON.stringify(list2),
        "parent_id": parent_id
      }


      this.axios.post('http://localhost:8080/update_menu', qs.stringify(data)).then(function (res) {

      })
    },


    /**
     * 判断该节点能否放置，下面做了在等级相同和放入高一级时的判断，放入等级相同时，可以放在前面和后面（prev,next），不可插入（inner）
     */
    allowDrop(draggingNode, dropNode, type) {
      if (dropNode.level === draggingNode.level) {
        return type === "prev" || type === "next";
      } else if (draggingNode.level - dropNode.level === 1) {
        return type === "inner"
      } else {
        return false;
      }
    },



    /**
     * 添加菜单
     */
    append(node, data) {
      if (node.level > 1) {
        alert("菜单最多两级")
        return;
      }
      let that = this;
      const newChild = {id: id++, label: 'undefined', children: []};
      if (!data.children) {
        this.$set(data, 'children', []);
      }
      let menu = {
        "title": newChild.label,
        "tag": data.idKey,
        "level_id": newChild.id,
      }
      this.axios.post('http://localhost:8080/addMenu', menu).then(function (res) {

        if (res.data.flag == "1") {
          newChild.idKey = res.data.id
          data.children.push(newChild);

        } else {
          alert("添加失败")
        }
      })
    },

    /**
     * 修改按钮打开该方法，将id赋值给selectedId传到对话框中去，在那边查该id的数据
     */
    update_menu(data) {
      this.selectedId = data.idKey
      this.dialogVisible = true;
    },


    /**
     * 删除菜单
     */
    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d.id === data.id);
      children.splice(index, 1);

      this.axios.post('http://localhost:8080/deleteMenu', qs.stringify({"id": data.idKey})).then(function (res) {

      })

    },

    /**
     * tree后面的附加内容
     */
    renderContent(h, {node, data, store}) {
      return (
        <span class="custom-tree-node">
            <span>{node.label}</span>
            <span>
              <el-button size="mini" type="text" on-click={() => this.append(node, data)}>添加</el-button>
              <el-button size="mini" type="text" on-click={() => this.update_menu(data)}>修改</el-button>
              <el-button size="mini" type="text" on-click={() => this.remove(node, data)}>删除</el-button>
            </span>
          </span>);
    }


  },


};
</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
